import json
import os
import pandas as pd

# 使用vote投票选举的方法对symbol选举，投出我们的文件节点所属的类别,并且保存到文件中

class Vote():
    def __init__(self,root):
        self.file_path=os.path.join(root,"raw","filedefsymbol.json")
        self.filepred = {}

    def vote2pred(self,dic, pred):
        '''
        通过投票的方法，得到我们的节点的预测值preds
        读取filejson文件，内容为每个文件包含的符号。
        Args:
            dic:
            file:
            pred:
            out:

        Returns:
        '''
        with open( self.file_path, 'r', encoding='utf8')as fp:
            json_data = json.load(fp)
            for file in json_data:
                vote = {}
                for symbol in file['symbol']:
                    if dic.get(str(symbol)) is not None:
                        _pred=pred[int(dic.get(str(symbol)))]
                        if vote.get(_pred) is None:
                            vote[_pred] = 1
                        else:
                            vote[_pred] += 1
                max_count = 0
                max_id = pred.max() + 1
                #如果所有的符号都不包含，则预测为k+1
                for pred_id in vote.keys():
                    symbol_count=vote[pred_id]
                    if int(symbol_count) > max_count:
                        max_id= pred_id
                        max_count = int(symbol_count)
                self.filepred[file['name']] = max_id
        return self.filepred
    '''
    输出到聚类文件中
    '''
    def predtofile(self, out):
        with open(out, 'w') as f:
            for k in self.filepred.keys():
                v = self.filepred.get(k)
                f.write("contain" + " " + str(v) + " " + str(k) + '\n')
        return self.filepred